package com.suxin;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * @author Tang
 * @classname Handler
 * @description [  ]
 * @date 2021/3/4 10:48
 */
public class Handler implements Runnable {

    protected Selector selector;
    protected SocketChannel sc;
    protected SelectionKey sk;

    ByteBuffer allocate = ByteBuffer.allocate(1024);

    public Handler(Selector selector, SocketChannel sc) {
        this.sc = sc;
        this.selector = selector;
        try {
            sc.configureBlocking(false);
            sk = sc.register(selector, SelectionKey.OP_READ);
            // attach 自己
            sk.attach(this);
            selector.wakeup();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        System.out.println("Handler.....");
        try {
            if (sk.isWritable()) {
                System.out.println("isWritable。。。。");
                enableRead();
            }
            if (sk.isReadable()) {
                // 读数据被触发，数据就要读出来，，不然事件 SelectionKey 不会消失，会一直触发
                doRead();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doRead() throws Exception {
        System.out.println("isReadable。。。。");
        int read = sc.read(allocate);
        processData(read);
    }

    public void processData(int readCount) {
        allocate.flip();
        System.out.println(new String(allocate.array()));
        allocate.clear();
        enableWriter();
    }


    public void enableWriter() {
        this.sk.interestOps(SelectionKey.OP_WRITE);
    }

    public void enableRead() {
        this.sk.interestOps(SelectionKey.OP_READ);
    }

}